﻿using Orchard.ContentManagement.MetaData;
using Orchard.Core.Contents;
using Orchard.Environment.Extensions.Models;
using Orchard.Security.Permissions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Codinlab.CustomClass.Permissions {
    public class CustomClassPermissions : IPermissionProvider {
        public static readonly Permission ManageCustomClassPart = new Permission { Description = "Manage Custom Class for all types", Name = "ManageCustomClass" };
        public static readonly Permission EditCustomClassPart = new Permission { Description = "Edit {0} Custom Class Part", Name = "EditCustomClass_{0}", ImpliedBy = new[] { CustomClassPermissions.ManageCustomClassPart } };

        private readonly IContentDefinitionManager _contentDefinitionManager;

        public Feature Feature { get; set; }

        public CustomClassPermissions(IContentDefinitionManager contentDefinitionManager) {
            _contentDefinitionManager = contentDefinitionManager;
        }

        public IEnumerable<Permission> GetPermissions() {
            var ccEnabledTypes = _contentDefinitionManager.ListTypeDefinitions()
                .Where(ctd => ctd.Parts.Where(ctpd => ctpd.PartDefinition.Name == "CustomClassPart").Any());

            foreach (var typeDefinition in ccEnabledTypes) {
                yield return DynamicPermissions.CreateDynamicPermission(EditCustomClassPart, typeDefinition);
            }

            yield return ManageCustomClassPart;
        }

        public IEnumerable<PermissionStereotype> GetDefaultStereotypes() {
            return new[] {
                new PermissionStereotype {
                    Name = "Administrator",
                    Permissions = new[] { ManageCustomClassPart }
                }
            };
        }
    }
}